<template>
  <div class="container">
    <div class="box">
      <div class="title">登录首页</div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="account">
          <el-input
            v-model="ruleForm.account"
            autocomplete="off"
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          @click="submitForm(ruleFormRef)"
          class="login-button"
        >
          登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { login } from "../api/login.js";
import router from "@/router";
import { userStore } from "@/store/user";

const user = userStore();
const ruleFormRef = ref();
const loading = ref(false); // 加载状态

const ruleForm = reactive({
  account: "",
  password: "",
});

const rules = reactive({
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const submitForm = async (formEl) => {
  if (!formEl) return;

  try {
    // 表单验证
    const valid = await formEl.validate();
    if (!valid) return;

    loading.value = true; // 开始加载

    const { account, password } = ruleForm;
    const res = await login({ account, password, role: 3 });

    if (res?.code === 0) {
      // 保存用户信息
      user.setUserInfo({
        ...res.data,
      });

      // 跳转到目标页面
      router.push("/home");
    } else {
      ElMessage.error(res?.message || "登录失败，请重试");
    }
  } catch (err) {
    ElMessage.error("登录失败，请检查网络或联系管理员");
  } finally {
    loading.value = false; // 结束加载
  }
};
</script>
<style scoped>
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
}

.title {
  margin-bottom: 35px;
  font-size: 17px;
  font-weight: bold;
  text-align: center;
}

.box {
  width: 400px;
  padding: 20px;
  box-shadow: 0px 0px 10px #e2dcdc;
  border-radius: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.demo-ruleForm {
  width: 100%;
}

.login-button {
  width: 100%;
  margin-top: 20px;
}
</style>
